<?php
namespace baofu;

require_once("Function/BFRSA.php");
require_once("Function/SdkXML.php");
require_once("Function/Log.php");
require_once("Function/HttpClient.php");

class Baofu {

    protected $version, $data_type, $txn_type, $member_id, $terminal_id, $private_key_password, $pfxfilename, $cerfilename, $request_url;

    public function __construct() {
        //header("Content-type: text/html; charset=utf-8");
        $this->version = "4.0.0.0";//版本号
        $this->data_type = "json";//加密报文的数据类型（xml/json）
        $this->txn_type = "0431";//交易类型

        //测试
        //$this->member_id = "100000276";    //商户号
        //$this->terminal_id = "100000990";    //终端号
        //$this->private_key_password = "123456";    //商户私钥证书密码
        //$this->pfxfilename = ROOT_PATH . 'api/payment/baofu/CER/bfkey_100000276@@100000990.pfx';  //注意证书路径是否存在
        //$this->cerfilename = ROOT_PATH . 'api/payment/baofu/CER/bfkey_100000276@@100000990.cer';//注意证书路径是否存在
        //$this->request_url = "https://tgw.baofoo.com/cutpayment/api/backTransRequest";  //测试环境请求地址

        //正式
        $this->member_id = "1189942";    //商户号
        $this->terminal_id = "36296";    //终端号
        $this->private_key_password = "623465";    //商户私钥证书密码
        $this->pfxfilename = EXTEND_PATH . 'baofu/CER/baofu.pfx';
        $this->cerfilename = EXTEND_PATH . 'baofu/CER/baofu.cer';
        $this->request_url = "https://public.baofoo.com/cutpayment/api/backTransRequest";
    }

    public function test(){
        echo 'hello world';exit;
    }

    public function ToSubmit($data) {
        GLOBAL $_G;
        $acc_no = isset($data["acc_no"]) ? trim($data["acc_no"]) : "";//银行卡卡号
        $id_card = isset($data["id_card"]) ? trim($data["id_card"]) : "";//身份证号码
        $id_holder = isset($data["id_holder"]) ? $data["id_holder"] : "";//姓名
        $mobile = isset($data["mobile"]) ? trim($data["mobile"]) : "";//银行预留手机号
        $trans_id = isset($data["trans_id"]) ? trim($data["trans_id"]) : "TI" . $this->get_transid() . $this->rand4();    //商户订单号
        $txn_sub_type = isset($data["txn_sub_type"]) ? trim($data["txn_sub_type"]) : "15";
        $pay_code = isset($data["pay_code"]) ? trim($data["pay_code"]) : "";//银行编码

        $biz_type = "0000";//接入类型
        $id_card_type = "01";//证件类型固定01（身份证）
        $acc_pwd = "";//银行卡密码（传空）
        $valid_date = "";//卡有效期 （传空）
        $valid_no = "";//卡安全码（传空）
        $additional_info = "";//附加字段
        $req_reserved = "";//保留
        $pay_cm = "2";//1:不进行信息严格验证,2:对四要素

        $trans_serial_no = "TSN" . $this->get_transid() . $this->rand4();    //商户流水号
        $trade_date = $this->return_time();    //订单日期

        $data_content_parms = array(
            //'pay_code' => $pay_code,
                'txn_sub_type' => $txn_sub_type,
                'biz_type' => $biz_type,
                'terminal_id' => $this->terminal_id,
                'member_id' => $this->member_id,
                'trans_serial_no' => $trans_serial_no,
                'trade_date' => $trade_date,
                'additional_info' => $additional_info,
                'req_reserved' => $req_reserved);

        $txn_amt = isset($data["txn_amt"]) ? trim($data["txn_amt"]) : 0;//交易金额额
        $txn_amt *= 100;//金额以分为单位（把元转

        if ($txn_sub_type == "01") { //01:直接绑卡类交易,
            $this->request_url = "https://public.baofoo.com/cutpayment/api/backTransRequest";
            $data_content_parms["acc_no"] = $acc_no;
            $data_content_parms["trans_id"] = $trans_id;
            $data_content_parms["id_card_type"] = $id_card_type;
            $data_content_parms["id_card"] = $id_card;
            $data_content_parms["id_holder"] = $id_holder;
            $data_content_parms["mobile"] = $mobile;
            $data_content_parms["acc_pwd"] = $acc_pwd;
            $data_content_parms["valid_date"] = $valid_date;
            $data_content_parms["valid_no"] = $valid_no;
            $data_content_parms["pay_code"] = $pay_code;
        } elseif ($txn_sub_type == "11") { //01:预绑卡类交易,
            $data_content_parms["acc_no"] = $acc_no;
            $data_content_parms["trans_id"] = $trans_id;
            $data_content_parms["id_card_type"] = $id_card_type;
            $data_content_parms["id_card"] = $id_card;
            $data_content_parms["id_holder"] = $id_holder;
            $data_content_parms["mobile"] = $mobile;
            $data_content_parms["acc_pwd"] = $acc_pwd;
            $data_content_parms["valid_date"] = $valid_date;
            $data_content_parms["valid_no"] = $valid_no;
            $data_content_parms["pay_code"] = $pay_code;
        } elseif ($txn_sub_type == "12") { //12:确认绑卡类交易,
            $sms_code = isset($_POST["sms_code"]) ? trim($_POST["sms_code"]) : "";//短信验证码
            $data_content_parms["sms_code"] = $sms_code;
            $data_content_parms["trans_id"] = $trans_id;
        } elseif ($txn_sub_type == "15") { //15:认证支付类预支付交易
            $ClientIp["client_ip"] = "100.0.0.0";//传用户的IP地址
            $data_content_parms["bind_id"] = $data['bind_id'];//获取绑定标识
            $data_content_parms["trans_id"] = $trans_id;//商户订单号
            $data_content_parms["risk_content"] = $ClientIp;
            $data_content_parms["txn_amt"] = $txn_amt;
        } elseif ($txn_sub_type == "16") { //16:认证支付类支付确认交易,
            if (!isset($data["business_no"]) || $data["business_no"] == '') {
                return ['status' => 0, 'msg' => 'business_no不能为空!'];
            }
            if (!isset($data["code"]) || $data["code"] == '') {
                return ['status' => 0, 'msg' => '验证码不能为空!'];
            }
            $data_content_parms["business_no"] = $data["business_no"];
            $data_content_parms["sms_code"] = $data["code"];
        }
        if ($this->data_type == "json") {
            $Encrypted_string = str_replace("\\/", "/", json_encode($data_content_parms));//转JSON
        } else {
            $toxml = new \SdkXML();    //实例化XML转换类
            $Encrypted_string = $toxml->toXml($data_content_parms);//转XML
        }
        \Log::LogWirte("序列化结果：" . $Encrypted_string);
        $BFRsa = new \BFRSA($this->pfxfilename, $this->cerfilename, $this->private_key_password); //实例化加密类。
        $Encrypted = $BFRsa->encryptedByPrivateKey($Encrypted_string);    //先BASE64进行编码再RSA加密
        $PostArry = array(
                "version" => $this->version,
                "terminal_id" => $this->terminal_id,
                "txn_type" => $this->txn_type,
                "txn_sub_type" => $txn_sub_type,
                "member_id" => $this->member_id,
                "data_type" => $this->data_type,
                "data_content" => $Encrypted);
        $return = \HttpClient::Post($PostArry, $this->request_url);  //发送请求到宝付服务器，并输出返回结果。
        \Log::LogWirte("请求返回参数：" . $return);
        if (empty($return)) {
            return '返回为空，确认是否网络原因！';
        }
        $return_decode = $BFRsa->decryptByPublicKey($return);//解密返回的报文
        \Log::LogWirte("解密结果：" . $return_decode . "\r\n===================================\r\n");
        $endata_content = array();
        if (!empty($return_decode)) {//解析XML、JSON
            if ($this->data_type == "xml") {
                $endata_content = \SdkXML::XTA($return_decode);
            } else {
                $endata_content = json_decode($return_decode, TRUE);
            }
            if (is_array($endata_content) && (count($endata_content) > 0)) {
                if (array_key_exists("resp_code", $endata_content)) {
                    if ($endata_content["resp_code"] == "0000") {
                        $return_decode = ['status' => 1, 'msg' => "订单状态码：" . $endata_content["resp_code"] . ", 商户订单号：" . $endata_content["trans_id"] . ", 返回消息：" . $endata_content["resp_msg"], 'url' => $this->request_url, 'return_data' => $endata_content];
                    } else {
                        //错误或失败其他状态
                        $return_decode = ['status' => 0, 'msg' => $endata_content["resp_msg"]];
                    }
                    return $return_decode;
                } else {
                    return ['status' => 0, 'msg' => "[resp_code]返回码不存在!"];
                }
            } else {
                return ['status' => 0, 'msg' => "返回数据有误!"];
            }
        } else {
            return ['status' => 0, 'msg' => "请求出错，请检查网络!"];
        }
    }

    function get_transid() {//生成时间戳

        return strtotime(date('Y-m-d H:i:s', time()));

    }

    function rand4() {//生成四位随机数

        return rand(1000, 9999);

    }

    function return_time() {//生成时间

        return date('YmdHis', time());

    }
}
